<?php

namespace app\admin\controller;

use app\admin\validate\AdminValidate;
use common\enum\ResultCode;
use app\admin\service\LoginService;
use hg\apidoc\annotation as Apidoc;
use support\Container;
use support\Request;
use support\Response;
use Tinywan\ExceptionHandler\Exception\BadRequestHttpException;

#[Apidoc\Title("登录管理")]
class LoginController extends BaseController
{
    private LoginService $service;
    protected AdminValidate $validate;

    public function __construct()
    {
        $this->service = Container::get(LoginService::class);
        $this->validate = Container::get(AdminValidate::class);
    }

    protected array $noNeedLogin = ['login'];
    protected array $noNeedAuth = ['logout'];

    #[Apidoc\Title("登录")]
    #[Apidoc\Url("admin/login/login")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Param("username", type: "string", require: true, desc: "账号")]
    #[Apidoc\Param("password", type: "string", require: true, desc: "密码")]
    #[Apidoc\Returned("token_type", type: "string", require: true, desc: "令牌类型")]
    #[Apidoc\Returned("expires_in", type: "int", require: true, desc: "有效时间")]
    #[Apidoc\Returned("access_token", type: "string", require: true, desc: "访问令牌")]
    #[Apidoc\Returned("refresh_token", type: "string", require: true, desc: "刷新令牌")]
    public function login(Request $request): Response
    {
        $username = $request->post('username');
        $password = $request->post('password');
        $data = ['user_name' => $username, 'password' => $password];
        if (!$this->validate->check($data, 'login')) {
            throw new BadRequestHttpException($this->validate->getError());
        }
        $result = $this->service->login($username, $password);
        return $this->success($result, ResultCode::LOGIN_SUCCESS->getDescription());
    }

    #[Apidoc\Title("退出登录")]
    #[Apidoc\Url("admin/login/logout")]
    #[Apidoc\Method("POST")]
    public function logout(): Response
    {
        $this->service->logout();
        return $this->success(null, ResultCode::LOGOUT_SUCCESS->getDescription());
    }
}